import re

title = re.compile('#*')
is_num = re.compile(r'^\d+')


def get_f2(f):
    fs = f.split('|')

    match = is_num.match(fs[1])
    if not match:
        return ''
    return fs[2] + ':' + fs[3]


# 读取md文件内容
def process_md_file(input_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.readlines()

    new_contents = []
    last_title_shape = ''  # 上一个表格包含的#

    temp_ls, row_num = [], 0
    for line in content:
        if temp_ls and row_num:
            new_contents.extend(temp_ls)

        temp_ls.clear()
        row_num = 0

        if line.startswith('#'):
            last_title_shape = title.match(line).group()
            t = line.replace(last_title_shape, f'\n\n{last_title_shape} ')+"\n"
            new_contents.append(t)
            continue

        if line.startswith('表名：'):
            temp_ls.append(f'\n{last_title_shape}# {line}\n\n')
            continue

        if line.startswith('|'):
            val = get_f2(line)
            if val:
                temp_ls.append(f'{last_title_shape}## {val}\n\n')
                row_num += 1
            continue

    if temp_ls and row_num:
        new_contents.extend(temp_ls)

    return new_contents


# 示例用法
input_file = 'D:\\x\\md\\table.md'  # 输入文件名

ns = process_md_file(input_file)
with open('out.md', 'w', encoding='utf-8') as f:
    f.writelines(ns)
print("转换完成！")
